package com.fleet.project01.activity;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import android.widget.ScrollView;
import androidx.appcompat.widget.Toolbar;

import com.fleet.project01.R;
import com.fleet.project01.data.api.RetrofitClient;
import com.fleet.project01.data.model.Post;
import com.fleet.project01.utils.LogUtils;
import com.fleet.project01.utils.NetworkUtils;
import com.fleet.project01.utils.ToastUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class PostDetailActivity extends AppCompatActivity {
    
    private static final String EXTRA_POST_ID = "extra_post_id";
    private static final String EXTRA_POST_TITLE = "extra_post_title";
    
    private TextView tvTitle;
    private TextView tvUserId;
    private TextView tvPostId;
    private TextView tvBody;
    private ScrollView contentLayout;
    private ProgressDialog progressDialog;
    
    private int postId;
    private String postTitle;

    public static void start(Context context, int postId, String title) {
        Intent intent = new Intent(context, PostDetailActivity.class);
        intent.putExtra(EXTRA_POST_ID, postId);
        intent.putExtra(EXTRA_POST_TITLE, title);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_post_detail);
        
        getIntentData();
        initViews();
        setupToolbar();
        loadPostDetail();
    }

    private void getIntentData() {
        Intent intent = getIntent();
        postId = intent.getIntExtra(EXTRA_POST_ID, 0);
        postTitle = intent.getStringExtra(EXTRA_POST_TITLE);
    }

    private void initViews() {
        tvTitle = findViewById(R.id.tvTitle);
        tvUserId = findViewById(R.id.tvUserId);
        tvPostId = findViewById(R.id.tvPostId);
        tvBody = findViewById(R.id.tvBody);
        contentLayout = findViewById(R.id.contentLayout);
        
        // 初始化ProgressDialog
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在加载文章详情...");
        progressDialog.setCancelable(false);
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    }

    private void setupToolbar() {
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        
        if (getSupportActionBar() != null) {
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
            getSupportActionBar().setTitle("文章详情");
        }
    }

    private void loadPostDetail() {
        if (!NetworkUtils.isNetworkConnected()) {
            ToastUtils.showShort("网络连接不可用，请检查网络设置");
            return;
        }

        showLoading(true);
        LogUtils.d("加载文章详情，ID: " + postId);

        Call<Post> call = RetrofitClient.getApiService().getPostById(postId);
        call.enqueue(new Callback<Post>() {
            @Override
            public void onResponse(Call<Post> call, Response<Post> response) {
                showLoading(false);
                
                if (response.isSuccessful() && response.body() != null) {
                    Post post = response.body();
                    LogUtils.d("获取文章详情成功: " + post.getTitle());
                    displayPostDetail(post);
                } else {
                    LogUtils.e("获取文章详情失败: " + response.code() + " - " + response.message());
                    ToastUtils.showShort("获取文章详情失败");
                    finish();
                }
            }

            @Override
            public void onFailure(Call<Post> call, Throwable t) {
                showLoading(false);
                LogUtils.e("网络请求失败: " + t.getMessage());
                ToastUtils.showShort("网络请求失败，请检查网络连接");
                finish();
            }
        });
    }

    private void displayPostDetail(Post post) {
        tvTitle.setText(post.getTitle());
        tvUserId.setText("作者ID: " + post.getUserId());
        tvPostId.setText("文章ID: " + post.getId());
        tvBody.setText(post.getBody());
    }

    private void showLoading(boolean isLoading) {
        if (isLoading) {
            // 显示模态框Loading
            if (progressDialog != null && !progressDialog.isShowing()) {
                progressDialog.show();
            }
            contentLayout.setVisibility(View.GONE);
        } else {
            // 隐藏模态框Loading
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
            contentLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 确保ProgressDialog被正确释放
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }
}
